package logbeam.business.agent;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.List;

import logbeam.business.Agent;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import crudbeam.business.BusinessPojo;
import crudbeam.database.DatabaseContainer;


public class AgentDatabaseContainer extends DatabaseContainer
		implements AgentContainer {

	private static Logger logger = Logger.getLogger( AgentDatabaseContainer.class );
	
	@Override
	@Transactional
	public BusinessPojo get( Long id ) {
		
		return (BusinessPojo) getCurrentSession().get( Agent.class, id );
	}
	
	@Override
	@SuppressWarnings( "unchecked" )
	@Transactional( readOnly = true )
	public Collection< Agent > getAll() {
	
		logger.info( "Executing query AgentDatabaseContainer.getAll" );

		List< Agent > agents = (List< Agent >) getCurrentSession().createCriteria( Agent.class )
				.addOrder( Order.asc( "name" ) )
				.list();
		
		logger.info( "Done" );
		return agents;
	}
	
	@Override
	@Transactional( readOnly = true )
	public Agent getByName( String name ) {

		@SuppressWarnings( "unchecked" )
		List< Agent > results = getCurrentSession().createCriteria( Agent.class )
			.add( Restrictions.eq( "name", name ) )
			.list();
		
		if ( !results.isEmpty() ) {
			return results.get( 0 );
		} else {
			return null;
		}
	}

	@Override
	@Transactional
	public void keepAlive( Agent agent ) {

		Agent lastKnownStatus = getByName( agent.getName() );
		
		if ( lastKnownStatus == null ) {
			agent.setLastReport( new Timestamp( System.currentTimeMillis() ) );
			save( agent );
		} else {
			if ( lastKnownStatus.getStatus() != agent.getStatus() || !lastKnownStatus.getStatusInformation().equals( agent.getStatusInformation() ) ) {
				lastKnownStatus.setStatus( agent.getStatus() );
				lastKnownStatus.setStatusInformation( agent.getStatusInformation() );
				lastKnownStatus.setLastReport( new Timestamp( System.currentTimeMillis() ) );
				save( lastKnownStatus );
			} else {
				lastKnownStatus.setLastReport( new Timestamp( System.currentTimeMillis() ) );
				save( lastKnownStatus );
			}
		}
	}
}
